<?php

use Javion\Image\Watermark;

function salesea_generate_taskid($prompt)
{
	$token = _wenda('gpt-key');
	$root_url = _wenda('gpt-api');
	if(empty($token) || empty($prompt)){
		return false;
	}
	$response = wp_remote_post($root_url, [
		'headers' => [
			'Authorization' => $token,
			'Content-Type' => 'application/json'
		],
		'body' => json_encode(["title" => $prompt])
	]);

	if ( is_wp_error( $response ) ) {
		$error_message = $response->get_error_message();
		$date = date('Y-m-d-H-i-s');
		file_put_contents(__DIR__."/errors/$date.txt", $error_message);
	} else {
		$data = wp_remote_retrieve_body( $response );
		// Use $data
		$array_data = json_decode($data, true);
		if($array_data['code'] == "ok"){
			$data = $array_data['data'];
			return $data;
		}else{
			return $array_data;
		}
	}
}

function salesea_format_keyword_and_question($keyword)
{
	$questions = _wenda('zhilingmoban');

	if(empty($questions)){
		return false;
	}

	//pick random question
	$question = $questions[array_rand($questions)];

	$replaced = str_replace("{关键词}", $keyword, $question['zhiling']);
	return $replaced;
}

function salesea_save_taskid_and_title_into_task($title, $keyword, $cat_id, $related)
{
	//prevent insert duplicate keyword into the table
	global $wpdb;
	$table_name = $wpdb->prefix . 'salesea_tasks';
	$sql = "SELECT * FROM $table_name WHERE keyword = '$keyword'";
	$rows = $wpdb->get_row( $sql );

	if(!empty($rows)){
		return false;
	}

	$questions = _wenda('zhilingmoban');
	if(empty($questions)){
		return false;
	}

	$image_url = '';
	$prompt = salesea_format_keyword_and_question($keyword);
	if($prompt){
		$task_id = salesea_generate_taskid($prompt);

		if(strlen(strval($task_id)) !== 19){
			return false;
		}

		if($task_id){
			$result = $wpdb->insert(
				$table_name,
				array(
					'taskid'    => $task_id,
					'keyword'  => $keyword,
					'title'   => $title,
					'prompt'   => $prompt,
					'related' => $related,
					'cat_id' => $cat_id,
					'img' => $image_url,
					'status' => 0
				)
			);
			return $result;
		}else{
			return false;
		}
	}else{
		return false;
	}
}

function salesea_check_task_status_and_return_content()
{
	global $wpdb;
	$token = _wenda('gpt-key');
	$root_url = _wenda('gpt-api');
	$table_name = $wpdb->prefix . 'salesea_tasks';
	$sql = "SELECT * FROM $table_name WHERE status = 0 LIMIT 1";
	$result_array = $wpdb->get_row( $sql );

	if(empty($result_array)){
		return false;
	}

	$task_id = $result_array->taskid;
	$title = $result_array->title;
	$keyword = $result_array->keyword;
	$prompt = $result_array->prompt;
	$cat_id = $result_array->cat_id;
	$image_url = $result_array->img;

	$response = wp_remote_get($root_url."/$task_id", [
		'headers' => [
			'Authorization' => $token,
			'Content-Type' => 'application/json'
		]
	]);

	if ( is_wp_error( $response ) ) {
		$error_message = $response->get_error_message();
		return $error_message;
	} else {
		$data = wp_remote_retrieve_body( $response );
		// Use $data
		$array_data = json_decode($data, true);
		if(isset($array_data['data']) && $array_data['data']['status'] === 2){
			$content = $array_data['data']['content'];
			$content = str_replace("null", "", $content);
			$wpdb->update($table_name, ['status' => 2], ['taskid' => $task_id]);
			$title = str_replace(PHP_EOL, ' ', $title);
			return ["id" => $task_id, "title" => $title, 'image' => $image_url, 'keyword' => $keyword, 'prompt' => $prompt, 'content' => $content, "cat_id" => $cat_id];
		}else{
			$wpdb->update($table_name, ['status' => $array_data['data']['status']], ['taskid' => $task_id]);
			return false;
		}
	}
}

function filter_symbols($string)
{
	$symbols = file_get_contents(__DIR__ . '/assets/symbols.txt');
	$symbols = str_replace("\r", '', $symbols);
	$symbols = array_filter(array_unique(explode("\n", $symbols)));
	return str_replace($symbols, '', $string);
}

function title_formatter($keyword, $relatedLists)
{
	$relatedLists = array_values($relatedLists);
	if ($relatedLists) {
		$related = $relatedLists[mt_rand(0, count($relatedLists) - 1)];
		$related = filter_symbols($related);

		if ($formats = _wenda('title-format')) {
			$formats = array_filter(explode('|', $formats));
			$format = $formats[mt_rand(0, count($formats) - 1)];
			$title = str_replace(
				array('{输入关键词}', '{联想词}'),
				array($keyword, $related),
				$format
			);
		} else {
			$title = "{$keyword}（{$related}）";
		}
		return array($title, $related);
	}

	$defaultTitle = _wenda('neizhibiaotikuozhan');
	$defaultTitle = $defaultTitle ? $defaultTitle : 'yes'; # 没有初始化情况

	if ('yes' == $defaultTitle) {
		if (mt_rand(1, 100) <= 50) {
			return array("{$keyword}的简单介绍", '');
		} elseif (mt_rand(1, 100) <= 50) {
			return array("关于{$keyword}的信息", '');
		}

		return array("包含{$keyword}的词条", '');
	}

	return array($keyword, '');
}

function diy_filter($string)
{

	$rules = _wenda("zidingyiguolv");

	if (empty($rules)) {
		return $string;
	}

	preg_match_all('/<.*?>/i', $string, $matches);
	$string = preg_replace('/<.*?>/i', '<!_!_!>', $string);
	$string = filter_escape($string);

	$rules = array_filter(explode("\n", $rules));
	$rules = is_array($rules) ? $rules : array();

	foreach ($rules as $item) {
		if ($values = array_filter(explode('<=>', $item))) {
			$rule = str_replace('*', '#@#', $values[0]);
			$rule = str_replace('#@#', '.*?', preg_quote($rule, '/'));
			$value = isset($values[1]) ? $values[1] : '';
			$string = preg_replace("/{$rule}/", $value, $string);
		}
	}

	$tags = is_array($matches[0]) ? $matches[0] : array();

	foreach ($tags as $tag) {
		$string = preg_replace('/\<\!\_\!\_\!\>/i', $tag, $string, 1);
	}

	return str_replace('<tag>', '', $string);
}


function salesea_convert_image($originalImage, $outputImage, $quality)
{
	// jpg, png, gif or bmp?
	$exploded = explode('.',$originalImage);
	$ext = $exploded[count($exploded) - 1];

	if (preg_match('/jpg|jpeg/i',$ext))
		$imageTmp=imagecreatefromjpeg($originalImage);
	else if (preg_match('/png/i',$ext))
		$imageTmp=imagecreatefrompng($originalImage);
	else if (preg_match('/gif/i',$ext))
		$imageTmp=imagecreatefromgif($originalImage);
	else if (preg_match('/bmp/i',$ext))
		$imageTmp=imagecreatefrombmp($originalImage);
	else
		return 0;

	// quality is a value from 0 (worst) to 100 (best)
	imagejpeg($imageTmp, $outputImage, $quality);
	imagedestroy($imageTmp);
	unlink($originalImage);
	return $outputImage;
}

function salesea_generate_image($text)
{
	$images = glob(__DIR__."/assets/pics_bg/*.jpg");
	$imagePath = $images[array_rand($images)];
	$image = new Watermark($imagePath);
	$random_img_name = strtolower(uniqid());
	$outputPath = __DIR__.'/output/' . $random_img_name;
	$image->waterImg(__DIR__ . '/assets/en_mb.png', 5, 60)->save(__DIR__."/output/", basename($outputPath));
	$imagePath = __DIR__."/output/".basename($outputPath).".png";
	$imagePath = salesea_convert_image($imagePath, __DIR__."/output/$random_img_name.jpg", 60);
	if(_wenda("lianxiangcisousuoyinqing") ==="谷歌")
	{
		$fonts = glob(__DIR__."/assets/fonts/*.ttf");
		$font = $fonts[array_rand($fonts)];
		$words = explode(' ', $text);
	}else{
		$font = __DIR__."/assets/zh40.ttf";
		$words = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
	}
	$image = imagecreatefromjpeg($imagePath);
	$fontSize = 24;
	$fontColor = imagecolorallocate($image, 23, 16, 16);
	$maxWidth = imagesx($image) * 0.8;
	$lines = array('');
	foreach ($words as $word) {
		$line = $lines[count($lines) - 1] . ' ' . $word;
		$bbox = imagettfbbox($fontSize, 0, $font, $line);
		if ($bbox[2] - $bbox[0] > $maxWidth) {
			array_push($lines, $word);
		} else {
			$lines[count($lines) - 1] = $line;
		}
	}
	$text = implode("\n", $lines);
	$textBox = imagettfbbox($fontSize, 0, $font, $text);
	$x = (imagesx($image) - $textBox[2]) / 2;
	$y = (imagesy($image) + $textBox[7]) / 2;
	imagettftext($image, $fontSize, 0, $x, $y, $fontColor, $font, $text);
	imagejpeg($image, $outputPath.".jpg");
	imagedestroy($image);
	return site_url("/wp-content/plugins/".plugin_basename(__DIR__)."/output/".basename($outputPath.".jpg"));
}







